
// 公共云对象
/**
	   * 生成 MD5 双重加密字符串
	   * @param {string} text - 待加密的文本
	   * @returns {string} MD5 哈希值（小写十六进制）
	   */
	  md5(text) {
	    if (typeof text !== 'string') {
	      text = String(text);
	    }
		const md5Text = crypto.createHash('md5')
		  .update(text, 'utf8')
		  .digest('hex');
	    return crypto.createHash('md5')
	      .update(md5Text, 'utf8')
	      .digest('hex');
	  }
module.exports = {
	_before: function () { // 通用预处理器

	},

	/**
	 * 作用：删除图片源文件
	 * filePth:要删除的图片路径
	 */
	async removeFileByPath(filePath){
		if(!filePath){
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: 'filePath参数不能为空'
			}
		}
		let result = await uniCloud.deleteFile({
		    fileList: [
		        filePath
		    ]
		});
		
		return {
			code:200,
			message:'删除成功',
			result:result
		}
	},
	
	/**
	 * 作用：更新职位表
	 */
	async updateArrayData(id,data){
		var db = uniCloud.database();
		var command = db.command;
		return await db.collection("userinfo_position").where({_id:id}).update({
						position:db.command.push(data)
					});
	},
	
	/**
	 * 更新视频点击量
	 */
	async setVideoClickInc(id){
		var db = uniCloud.database();
		var command = db.command;
		return db.collection('video').where({_id:id}).update({
			click:command.inc(1)
		});
	},
	
	/**
	 * 作用：根据年月日生成订单号
	 * 
	 */
	async getOrderNumber() {
	    // 获取当前日期时间
	    const date = new Date();
	    
	    // 提取年月日时分秒
	    const year = date.getFullYear();
	    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
	    const day = String(date.getDate()).padStart(2, '0');
	    const hours = String(date.getHours()).padStart(2, '0');
	    const minutes = String(date.getMinutes()).padStart(2, '0');
	    const seconds = String(date.getSeconds()).padStart(2, '0');
	    
	    // 生成5位随机数（10000-99999之间）
	    const randomNum = Math.floor(10000 + Math.random() * 90000);
	    
	    // 拼接成订单号
	    const orderNumber = `GS${year}${month}${day}${hours}${minutes}${seconds}${randomNum}`;
	    
	    return orderNumber;
	},
	
	/**
	 * 添加商品后更新商品对应分类的商品数量
	 */
	async updateGoodsNumberByCategory(categoryArray,item = null){
		if(!categoryArray || !categoryArray[0] || !categoryArray[1]){
			return {
				code:100,
				message:'参数错误'
			}
		}
		var db = uniCloud.database();
		var cmd = db.command;
		//更新大类的商品数量
		if(item == null || !item){
			var stepNumber = 1;
		}else if(item == 'dec'){
			var stepNumber = -1;
		}
		var result = await db.collection('category').where({_id:categoryArray[0]}).update({
			goods_number:cmd.inc(stepNumber)
		});
		//更新小类商品
		var category = await db.collection('category').where({_id:categoryArray[0]}).get();
		var children = category.data[0].children;
		const index = children.findIndex(item => item._id == categoryArray[1]);
		var goods_number = 0;
		if(children && children[index] && children[index].goods_number){
			goods_number  = children[index].goods_number;
		}
		
		const number = goods_number + stepNumber;
		children[index].goods_number = number;
		var data = {
			children:children
		}
		if(categoryArray && categoryArray[0]){
			//更新到数据库
			var updateReuslt = await db.collection('category').where({_id:categoryArray[0]}).update(data);
		}
		
		return {
			code:200,
			message:'更新成功',
			result:{
				category:result,
				children:updateReuslt
			}
		}
		
	},
	
	/**
	 * 作用：更新订单状态
	 */
	async updateOrderStatus(orderNo,data){
		var db = uniCloud.database();
		var result = await db.collection('order').where({order_no:orderNo}).update({
			status:db.command.push(data)
		});
		return {
			code:200,
			message:'更新成功',
			result:result
		}
	},
	
	/**
	 * 作用：调用第三方物流信息
	 */
	async getWuliu(com,num,phone){
		var url = 'https://poll.kuaidi100.com/poll/query.do';
		var key = 'ZgPbdBgu2447';
		var customer = 'AFA4C1283E4521BFDE5550077CE42A35';
		var param = {
			com:com,
			num:num,
			phone:phone,
			order:'desc'
		}
		var sign = md5(param+key+customer);
		param.sign = sign;
		const result = await uniCloud.request({
		        url: url,
		        method: 'POST',
		        data: data
		      });
			  
	  return result;
	}
}
